import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';
import { User } from './entities/user.entity';
import { Role } from './entities/role.entity';
import { Permission } from './entities/permission.entity';
import { Menu } from './entities/menu.entity';
import { UserRole } from './entities/user-role.entity';
import { RolePermission } from './entities/role-permission.entity';
import { RoleMenu } from './entities/role-menu.entity';
import { PaymentOrder } from './entities/payment-order.entity';
import { Script } from './entities/script.entity';
import { ScriptExecution } from './entities/script-execution.entity';
import { CopilotConfig } from './entities/copilot-config.entity';
import { CopilotRequestLog } from './entities/copilot-request-log.entity';
import { CopilotFieldMapping } from './entities/copilot-field-mapping.entity';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        type: 'mysql',
        host: configService.get('DB_HOST', 'localhost'),
        port: configService.get('DB_PORT', 3306),
        username: configService.get('DB_USERNAME', 'root'),
        password: configService.get('DB_PASSWORD', ''),
        database: configService.get('DB_DATABASE', 'system_admin'),
        entities: [
          User,
          Role,
          Permission,
          Menu,
          UserRole,
          RolePermission,
          RoleMenu,
          PaymentOrder,
          Script,
          ScriptExecution,
          CopilotConfig,
          CopilotRequestLog,
          CopilotFieldMapping,
        ],
        namingStrategy: new SnakeNamingStrategy(),
        synchronize: configService.get('NODE_ENV') === 'development',
        logging: configService.get('NODE_ENV') === 'development',
        timezone: '+08:00',
        charset: 'utf8mb4',
      }),
      inject: [ConfigService],
    }),
  ],
})
export class DatabaseModule {}